package com.hontech.libratest.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.core.content.FileProvider
import com.hontech.libratest.app.AppContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.reflect.KSuspendFunction0

fun hideSoftKey(activity: Activity) {
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (!imm.isActive) {
        return
    }
    val view = activity.currentFocus
    if (view == null) {
        return
    }
    imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun showToast(msg: String) {
    Toast.makeText(AppContext, msg, Toast.LENGTH_SHORT).show()
}


val eventBus = EventBus.builder().logNoSubscriberMessages(false).build()

val appScope = CoroutineScope(Job() + Dispatchers.Main)

fun View.onClick(fn: KSuspendFunction0<Unit>) {

    this.setOnClickListener {
        appScope.launch {
            try {
                fn()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

fun EditText.toInt(base: Int = 10): Int {
    val s = this.text.toString()
    return s.toInt(base)
}

fun dimenById(id: Int): Int {
    return AppContext.resources.getDimension(id).toInt()
}

private val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

fun currentTime(): String {
    val dt = Calendar.getInstance()
    return format.format(dt.time)
}

fun formatDate(timestamp: Long): String {
    val date = Date(timestamp * 1000)
    return format.format(date)
}

fun installApp(path: String) {
    val uri = FileProvider.getUriForFile(
        AppContext,
        "com.hontech.libratest.FileProvider",
        File(path)
    )
    val i = Intent(Intent.ACTION_VIEW)
    i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    i.addCategory("android.intent.category.DEFAULT")
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    i.setDataAndType(uri, "application/vnd.android.package-archive")
    AppContext.startActivity(i)
}

fun saveFile(data: ByteArray, name: String): String {
    val file = File(Environment.getExternalStorageDirectory(), name)
    if (!file.exists()) {
        val ret = file.createNewFile()
        if (!ret) {
            throw IOException("创建文件失败")
        }
    }
    val out = FileOutputStream(file, false)
    out.write(data)
    out.close()

    return file.path
}


val PackageName = AppContext.packageName
val Version = AppContext.packageManager.getPackageInfo(PackageName, 0).versionName

val defJson = Json {
    ignoreUnknownKeys = true
    encodeDefaults = true
}

inline fun<reified T> ByteArray.decodeJson(): T {
    return defJson.decodeFromString(String(this, Charsets.UTF_8))
}

fun startWeb(url: String) {
    val intent = Intent()
    intent.setAction("android.intent.action.VIEW")
    intent.setData(Uri.parse(url))
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    AppContext.startActivity(intent)
}

fun canExternalStore(): Boolean {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
        return Environment.isExternalStorageManager()
    }
    return true
}

fun canWriteFile(): Boolean {

    var ret = AppContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
    if (!ret) {
        return false
    }

    try {
        ret = canExternalStore()
        if (ret) {
            return true
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return false
}



